<template>
  <div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="left-side">
      <!-- 搜索框 -->
      <div class="search-wrapper">
        <el-input
          v-model="searchUserName"
          placeholder="回车搜索用户"
          class="search-input"
          @keydown.enter.native="searchUserForForm"
        ></el-input>
      </div>

      <!-- 用户列表 -->
      <el-scrollbar class="user-list-scroll">
        <el-row v-if="messageForm.length > 0">
          <el-col
            v-for="form in messageForm"
            :key="form.sendUser.userId"
            @click.native="chooseUser(form.sendUser)"
            class="user-item"
          >
            <div class="user-avatar-wrapper">
              <div :class="{ 'online-dot': form.isOnline }"></div>
              <!-- 未读消息徽章 -->
              <el-badge
                :value="form.unreadCountUser2"
                class="message-badge"
                v-if="form.unreadCountUser2 > 0"
              >
                <img :src="form.sendUser.avatar" class="user-avatar" />
              </el-badge>
              <img v-else :src="form.sendUser.avatar" class="user-avatar" />
            </div>

            <div class="user-details">
              <div class="user-name">{{ form.sendUser.userName }}</div>
              <div class="user-last-message">{{ form.lastMessage }}&nbsp;</div>
              <div class="user-last-time">
                {{ form.lastMessageTime | timePart }}&nbsp;
              </div>
              <div class="user-status">{{ form.status }}</div>
            </div>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <div v-else class="no-users">暂无用户</div>
      </el-scrollbar>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="right-side">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <span v-if="currentUser">{{ currentUser.userName }}</span>
        <span v-else>请选择会话</span>
      </div>

      <!-- 消息区域 -->
      <el-scrollbar class="chat-messages" ref="messageContainer">
        <div class="messages-wrapper">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message-box"
            :class="{
              'own-message': message.senderId === loginUser.userId,
              'other-message': message.senderId !== loginUser.userId,
            }"
          >
            <!-- 头像 -->
            <div class="avatar">
              <img
                :src="
                  message.senderId === loginUser.userId
                    ? loginUser.avatar
                    : currentUser?.avatar
                "
                alt="用户头像"
              />
            </div>

            <!-- 消息内容 -->
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">
                {{ message.createTime | timePart }}
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="newMessage.content"
          placeholder="请输入聊天内容"
          autosize
          class="message-input"
          @keydown.enter.native="sendMessage"
        ></el-input>
        <el-button
          type="primary"
          @click.native="sendMessage"
          class="send-button"
          >发送</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import {
  reqSendMessage,
  reqGetConversations,
  reqGetHistory,
  reqReadMessage,
  reqDeleteMessage,
  reqGetUnreadCount,
  reqReadConversation,
} from "@/api";
// import websocket from "@/utils/websocket";
export default {
  name: "PrivateMessage",
  filters: {
    timePart(value) {
      return this.getTimePart(value);
    },
  },
  data() {
    return {
      currentUser: null, // 当前聊天的人
      loginUser: null,
      messages: [],
      messageForm: [], // 聊天所有信息
      newMessage: {
        messageType: "",
        receiveId: "",
        content: "",
        fileUrl: "",
      },
      searchUserName: "",
    };
  },
  methods: {
    getTimePart(dateTime) {
      if (!dateTime) return ""; // 处理空值
      // 用正则分割（支持空格或T分隔），取后面的时间部分
      const parts = dateTime.split(/[\sT]/); // 匹配空格或T
      return parts.length > 1 ? parts[1] : dateTime; // 没有时间部分则返回原字符串
    },
    async fetchMessages(userId) {
      if (!userId) {
        this.reqGetConversations();
        return;
      }
      if (this.userId == null) {
        this.$message.error("登录用户编号获取失败,请重新登录!");
        return;
      }
      const res = await reqGetHistory(userId);
      if (res.code === 200) {
        this.$message(res.message);
        this.messages = res.data;
        // 将聊天记录总下拉到最下方
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } else {
        this.$message.error("获取聊天记录失败");
        return;
      }
    },
    sendMessage() {
      if (!this.newMessage.content.trim()) {
        this.$message.warning("请输入聊天内容");
        return;
      }
      this.newMessage.content = this.newMessage.content.trim();
      if (this.loginUser.userId == null) {
        this.$message.error("登录用户编号获取失败,请重新登录!");
        return;
      }
      // if (this.loginUser.userId === this.currentUser.userId) {
      //   this.$message.error("不能给自己发送信息!");
      //   return;
      // }//看情况
      this.newMessage.receiveId = this.currentUser.userId;
      //看情况修改内容
      // this.newMessage.messageType = "text";
      // this.newMessage.fileUrl = "";
      this.sendWebSocketMessage(this.newMessage);
      reqSendMessage(this.newMessage).then((res) => {
        if (res.code !== 200) {
          this.$message.error("消息发送失败!");
          return;
        }
        this.chooseUser(this.currentUser);
      });
    },
    // 消息过多的时候滚动到最新消息位置
    scrollToBottom() {
      // 使用 $refs 来获取对消息容器的引用
      const container = this.$refs.messageContainer.$refs.wrap;
      // 滚动到底部
      container.scrollTop = container.scrollHeight;
    },
    checkAvatar(avatar) {
      if (avatar && avatar !== undefined) {
        return avatar;
      }
      return "";
    },
    chooseUser(user) {
      this.currentUser = user;
      this.fetchMessages(user.userId);
    },
    // websocket
    async connectWebSocket(userId) {
      await new Promise((resolve) => {
        websocket.Init(userId);

        // 在 WebSocket 连接成功时调用 resolve
        websocket.getWebSocket().onopen = () => {
          console.log("WebSocket连接成功");
          resolve();
        };
      });
    },
    // 发送信息
    sendWebSocketMessage(message) {
      websocket.getWebSocket().onmessage = (event) => {
        // 处理消息，这里你可以根据实际需求更新页面上的数据
        console.log("收到的消息WebSocket2:", event);
        // 更新收到的消息
        // receivedMessage.value = event.data
        if (this.currentUser) {
          this.fetchMessages(this.currentUser.userId);
        } else {
          this.reqGetConversations();
        }
      };
    },
    handleMessage(message) {
      // 内容进行相应的处理
      const parsedMessage = JSON.parse(message);
      console.log("收到信息:", parsedMessage);
      if (this.currentUser) {
        this.fetchMessages(this.currentUser.userId);
      } else {
        this.reqGetConversations();
      }
    }, // 获取所有信息
    async reqGetConversations() {
      if (this.loginUser !== null) {
        const res = await reqGetConversations();
        if (res.code == 200) {
          this.$message(res.message);
          this.messageForm = res.data;
        } else {
          this.$message.error("获取聊天记录失败");
          return;
        }
      }
    },
    // 初始化websocket
    async connectWebSocket(userId) {
      await new Promise((resolve) => {
        websocket.Init(userId);

        // 在 WebSocket 连接成功时调用 resolve
        websocket.getWebSocket().onopen = () => {
          console.log("WebSocket连接成功");
          resolve();
        };
      });
    },
  },
  computed: {
    userId() {
      return this.$store.state.user.userForm.userId;
    },
  },
  mounted() {
    websocket.setMessageCallback((res) => {
      this.handleMessage(res);
    });
  },
  created() {
    // 确保在使用userId时，userId被创建出来了
    if (this.userId) {
      this.connectWebSocket(this.userId);
      this.loginUser = this.$store.state.user.userForm;
      this.reqGetConversations();
    } else {
      console.warn("未获取到有效userId");
    }
  },
  // 如果 userId 可能动态变化，可添加 watch 来响应变化
  // watch: {
  //   userId(newId) {
  //     if (newId) {
  //       websocket.closeConnection();
  //       this.connectWebSocket(newId);
  //     }
  //   },
  // },
  beforeDestroy() {
    // 4. 添加组件销毁时的清理
    // websocket.closeConnection();
  },
};
</script>

<style scoped lang="scss">
// 主题变量
$primary-color: #70c1fa;
$secondary-color: #eceff1;
$success-color: #d1f7d1;
$error-color: #f56c6c;
$avatar-border: 1px solid #74ffd2;
$online-dot-color: #01c201;

$radius-circle: 50%;
$radius-default: 8px;
$spacing-xs: 5px;
$spacing-sm: 10px;
$spacing-md: 20px;

// 基础样式
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

@mixin text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-container {
  display: flex;
  height: 100%;
  background: linear-gradient(to bottom right, #ffffff, $secondary-color);
}

/* 左侧区域 */
.left-side {
  position: relative;
  flex: 1;
  padding: $spacing-md;
  border-right: 1px solid #eaeaea;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

  .search-wrapper {
    position: absolute;
    top: $spacing-md;
    left: $spacing-md;
    right: $spacing-md;

    .search-input {
      width: 100%;
    }
  }

  .user-list-scroll {
    position: absolute;
    top: 60px;
    bottom: 0;
    left: 0;
    right: 0;
    overflow-y: auto;

    .no-users {
      @include flex-center;
      height: 100%;
      color: #999;
      font-size: 14px;
    }
  }

  .user-item {
    display: flex;
    align-items: center;
    padding: $spacing-sm;
    border-bottom: 1px solid #f0f0f2;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #f5f5f5;
    }

    .user-avatar-wrapper {
      position: relative;
      display: inline-block;
      margin-right: $spacing-sm;

      .online-dot {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 10px;
        height: 10px;
        background-color: $online-dot-color;
        border-radius: $radius-circle;
        border: 1px solid #fff;
      }

      .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: $radius-circle;
        border: $avatar-border;
      }

      .message-badge {
        position: relative;

        .el-badge__content {
          position: absolute;
          bottom: $spacing-xs;
          left: $spacing-xs;
          background-color: $error-color;
          color: white;
          font-size: 12px;
          min-width: 16px;
          height: 16px;
          line-height: 16px;
          padding: 0 4px;
          border-radius: 8px;
          transform: translateY(-50%);
          transform-origin: center;
        }
      }
    }

    .user-details {
      flex: 1;
      overflow: hidden;

      .user-name {
        @include text-ellipsis;
        font-weight: 800;
        font-size: 14px;
        padding-left: 15px;
        text-align: left;
      }

      .user-last-message {
        @include text-ellipsis;
        color: #a19f9f;
        font-size: 13px;
        padding-left: 15px;
        text-align: left;
      }
      .user-last-time .user-status {
        @include text-ellipsis;
        font-size: 11px;
        padding-right: 15px;
        padding-bottom: 5px;
        text-align: right;
      }
    }
  }
}

/* 右侧区域 */
.right-side {
  flex: 3;
  display: flex;
  flex-direction: column;

  .chat-header {
    padding: $spacing-md;
    border-bottom: 1px solid #eaeaea;
    font-size: 1.2em;
    color: #37474f;
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: $spacing-md;

    .messages-wrapper {
      display: flex;
      flex-direction: column;
      gap: $spacing-sm;
    }
  }

  .message-box {
    display: flex;
    align-items: start;
    gap: $spacing-sm;

    .avatar {
      flex-shrink: 0;

      img {
        width: 40px;
        height: 40px;
        border-radius: $radius-circle;
        border: 1px solid $primary-color;
      }
    }

    .message-content {
      display: flex;
      flex-direction: column;
      max-width: 70%;
    }

    .message-text {
      padding: $spacing-sm $spacing-md;
      border-radius: $radius-default;
      background-color: #f0f0f0;
      text-align: left;
      word-wrap: break-word;
      font-size: 14px;
    }

    .message-time {
      font-size: 12px;
      color: #999;
      margin-top: $spacing-xs;
      align-self: flex-end;
    }
  }

  .own-message {
    flex-direction: row-reverse;

    .message-text {
      background-color: $success-color;
    }

    .message-time {
      align-self: flex-end;
    }
  }

  .other-message {
    flex-direction: row;

    .message-time {
      align-self: flex-start;
    }
  }

  .chat-input {
    padding: $spacing-md;
    display: flex;
    align-items: center;
    border-top: 1px solid #eaeaea;

    .message-input {
      flex: 1;
      margin-right: $spacing-sm;
    }

    .send-button {
      flex-shrink: 0;
    }
  }
}
</style>